const { UNKNOWN_ERROR } = require("../config/error-constants");
const labelService = require("../service/label.service");
const { to } = require("../utils");

// 额外中间件：验证label的name是否存在于label表中
const verifyLabelName = async (ctx, next) => {
    // 1.取出参数labels
    const { labels } = ctx.request.body;
    // 记录上下文labels(id,name)
    const newLabels = [];
    // 2.遍历labels
    for (const name of labels) {
        const { id } = ctx.user;
        const labelObj = { name };
        // 2.1. 判断name是否存在于label表中
        const [error, resp] = await to(labelService.findLabelByName(name));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }
        // 2.2. 取出数据库查询的结果,如果存在记录，直接跳过；如果不存在这条记录，创建标签;
        if (!!resp) {
            labelObj.id = resp.id;
        }
        if (!resp) {
            const [error, resp] = await to(labelService.create(name, id));
            if (error) {
                return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
            }
            labelObj.id = resp.insertId;
        }
        newLabels.push(labelObj);
    }

    ctx.labels = newLabels;

    await next();
};

module.exports = verifyLabelName;
